package cn.zhp.service.impl;

import cn.zhp.entity.SysArea;
import cn.zhp.listener.SysAreaListener;
import cn.zhp.mapper.SysAreaMapper;
import cn.zhp.service.SysAreaService;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@Service
@Transactional

public class SysAreaServiceImpl extends BaseServiceImpl<SysArea> implements SysAreaService {

    @Autowired
    SysAreaMapper sysAreaMapper;


    


    /**
     * 根据父区域id或者区域名或者不带条件查找所有区域
     * @return
     *
     *
     */
    @Override
    public PageInfo<SysArea> selectPage(int pageNum, int pageSize, Map<String, Object> params) {
        //{"aid":''}        {}
        PageInfo<SysArea> pageInfo = null;
        PageHelper.startPage(pageNum,pageSize);
        //根据父区域id/父级区域名的查询

        List<SysArea> list = sysAreaMapper.selectByPid(params);
        pageInfo = new PageInfo<>(list);

        return pageInfo;
    }

   /* @Override
    public SysArea selectByAid(long id) {
        SysArea sysArea = sysAreaMapper.selectByAid(id);
        sysArea.setOldParentIds(sysArea.getParentIds());//给旧parentIds绑定数据
        return sysArea;
    }*/

    /*
    * 重写  动态更新方法:
    * 1.更新本区域信息
    * 2.如果parentIds和oldParentIds不一致，则说明本区域的父级区域发生改变，需要修改本区域所有子级区域的
    * parentIds
    *
    * */

    @Override
    public int updateByPrimaryKeySelective(SysArea sysArea) {
        int result = 0;
        try {
            result = mapper.updateByPrimaryKeySelective(sysArea);

            String parentIds = sysArea.getParentIds();
            String oldParentIds = sysArea.getOldParentIds();
            if (!StringUtils.isEmpty(parentIds) && !StringUtils.isEmpty(oldParentIds)) {
                if (!parentIds.equals(oldParentIds)) {//需要更新子级区域的parentIds

                    result += sysAreaMapper.updateParentIds(sysArea);

                }
            }
        }catch (Exception e){
            throw new RuntimeException("更新失败，请重试");
        }
        return result;
    }

    /**
     *
     * @param outputStream  当前客户端的响应流对象
     */
    @Override
    public void download(OutputStream outputStream){
        EasyExcel.write(outputStream,SysArea.class).sheet().doWrite(sysAreaMapper.selectAll());
    }

    /**
     *
     * @param inputStream  当前客户端上传的文件流对象
     */
    @Override
    public void upload(InputStream inputStream){
        //在easyexcel的监听对象中  通过构造器传入  mapper对象  不要使用spring的注入方式注入
        EasyExcel.read(inputStream,SysArea.class,new SysAreaListener(sysAreaMapper)).sheet().doRead();
    }
}
